<template>
  <div>
    <el-form ref="myform" label-width="120px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="服务工作总次数">
            <el-input v-model="totalNumber" placeholder="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务工作总耗时(分)">
            <el-input v-model="totalTime" placeholder="0" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="详细">
            <PageableTable :loading="false" :table-height="800" :data="tableData" :span-method="objectSpanMethod" :disable-pageable="true" class="fixed-table-table">
              <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
            </PageableTable>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <slot />
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>

import { list as dayList } from '@neu/dcom-ui/api/workDaily'
import { serviceSummaryByMonthId, updateServiceSummary, detail } from '@neu/dcom-ui/api/monthWeekly'
import { list as typeList } from '@neu/dcom-ui/api/serviceType'
import { deepClone } from '@neu/biz-core/utils'
import PageableTable from '@neu/biz-core/components/PageableTable'
import { monthBegin, monthEnd } from '@neu/biz-core/utils/utils'

export default {
  name: 'ServiceSummaryForm',
  components: {
    PageableTable
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      totalNumber: 0,
      totalTime: 0,
      rules: {},
      // 表格
      insideColumns: [
        { title: '服务类型', key: 'serviceTypeName' },
        { title: '服务属性', key: 'serviceAttributesName' },
        { title: '总次数', key: 'totalNumber',
          render: (h, params) => {
            return (
              <div>
                <el-input-number v-model={params.row.totalNumber} min={0} max={999999} change={this.getServiceTotalNumber(this.tableData)}/>
              </div>
            )
          }
        },
        { title: '总耗时(分钟)', key: 'totalTime',
          render: (h, params) => {
            return (
              <div>
                <el-input-number v-model={params.row.totalTime} min={0} max={999999} change={this.getServiceTotalTime(this.tableData)}/>
              </div>
            )
          }
        }
      ],
      // tableData: [],
      serviceSummary: [],
      typeList: [],
      spanSetting: {}

    }
  },
  computed: {
    tableData: function() {
      const result = []
      const typeList = deepClone(this.typeList) || []
      const serviceSummary = deepClone(this.serviceSummary) || []
      typeList.forEach(k => {
        let index = 0
        const data = k.children.map(s => {
          const item = serviceSummary.find(l => l.serviceTypeCode === k.code && l.serviceAttributesCode === s.code)
          const serviceTypeName = k.title
          const serviceTypeCode = k.code
          const serviceAttributesName = s.title
          const serviceAttributesCode = s.code
          const totalNumber = item ? item.totalNumber : 0
          const totalTime = item ? item.totalTime : 0
          const span = [index === 0 ? k.children.length : 0, index === 0 ? 1 : 0]
          index = 1
          return { serviceTypeName, serviceTypeCode, serviceAttributesName, serviceAttributesCode, totalNumber, totalTime, span }
        })
        result.push(...data)
      })
      this.getServiceTotalNumber(result)
      this.getServiceTotalTime(result)
      return result
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    typeList().then(res => {
      this.typeList = res.data
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        serviceSummaryByMonthId(this.id).then(res => {
          if (res.data.length > 0) {
            this.serviceSummary = res.data
          } else {
            detail(this.id).then(response => {
              const { clientCode } = response.data
              if (clientCode) {
                const obj = {
                  s_unitCode: clientCode,
                  s_afEqReportDate: monthBegin(new Date().getTime()),
                  s_beEqReportDate: monthEnd(new Date().getTime())
                }
                dayList(obj).then(re => {
                  const data = re.data
                  if (data.length > 0) {
                    this.serviceSummary = data.reduce((groups, item) => {
                      var groupFound = groups.find(arrItem => item.serviceTypeCode === arrItem.serviceTypeCode && item.serviceAttributesCode === arrItem.serviceAttributesCode)
                      if (groupFound) {
                        groupFound.totalNumber += 1
                        groupFound.totalTime += item.totalWorkingHours
                      } else {
                        // 不要直接在原来的对象修改，新建对象
                        var newGroup = {
                          serviceTypeName: item.serviceTypeName,
                          serviceTypeCode: item.serviceTypeCode,
                          serviceAttributesName: item.serviceAttributesName,
                          serviceAttributesCode: item.serviceAttributesCode,
                          totalNumber: 1,
                          totalTime: item.totalWorkingHours
                        }
                        groups.push(newGroup)
                      }
                      return groups
                    }, [])
                  }
                })
              }
            })
          }
        })
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        if (updated) {
          resolve(updateServiceSummary(this.id, this.tableData))
        } else {
          resolve(false)
        }
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    getServiceTotalNumber(list) {
      const total = list.map(e => e.totalNumber)
      this.totalNumber = total.length > 0 ? total.reduce((n, m) => n + m) : 0
    },
    getServiceTotalTime(list) {
      const total = list.map(e => e.totalTime)
      this.totalTime = total.length > 0 ? total.reduce((n, m) => n + m) : 0
    },
    getSpan(typeList) {
      const result = {}
      for (let j = 1; j <= typeList.length; j++) {
        for (let i = 1; i <= typeList[j].children.length; i++) {
          if (i === 0) {
            result[i * j] = [typeList[j].children.length, 0]
          }
        }
      }
      return result
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return row.span
      }
    }
  }
}
</script>
